package com.xy.service;

import com.xy.lock.RedisLock;
import com.xy.mapper.TestMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.UUID;

/**
 * @author xxy
 * @date 2022/1/5 13:04
 */
@Service
public class TestService {

    private final TestMapper testMapper;
    private final RedisLock redisLock;

    public TestService(TestMapper testMapper,
                       RedisLock redisLock) {
        this.testMapper = testMapper;
        this.redisLock = redisLock;
    }

    @Transactional
    public int updateNum() {

        int num = testMapper.getNum();
        num++;
        testMapper.updateNum(num);
        return num;

    }


    public Map test() {
        Map result = new HashMap();

        long num = 0;
        long time = 10;
        String reqId = UUID
                .randomUUID()
                .toString()
                .replace("-", "") + (new Random()
                .nextInt(9000) + 1000);

        Thread t1 = null;

        try {
            // 尝试获取锁
            redisLock.tryGetLock(reqId, time);
            // 创建子线程续命
            t1 = redisLock.createLifeThread(time, reqId);
            // t1 线程开启守护线程
            t1.setDaemon(true);
            // 启动 t1 线程
            t1.start();

            result.put("num", updateNum());
            result.put("reqId", reqId);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 中断 t1 线程
            t1.interrupt();
            // 释放锁
            redisLock.unLock(reqId);
        }

        return result;
    }


}
